import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/home'
  },
  // 主页面
  {
    path: '/home',
    component: () => import('../views/home/Home.vue'),
    redirect: 'welcome',
    children: [
      // 欢迎页面
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('../views/home/Welcome.vue')
      },
      // 管理员
      {
        path: '/admin',
        component: () => import('@/views/admin/Admin.vue')
      },
      // 全部志愿者
      {
        path: '/volunteer',
        component: () => import('@/views/volunteer/Volunteer.vue')
      },
      // 全部活动
      {
        path: '/activityall',
        component: () => import('@/views/activity/Activityall.vue')
      },
      // 百姓生活
      {
        path: '/life',
        component: () => import('@/views/life/Life.vue')
      },
      // 社区
      {
        path: '/community',
        component: () => import('@/views/community/Community.vue')
      },
      // 审核志愿者
      {
        path: '/check',
        component: () => import('@/views/volunteer/CheckVolunteer.vue')
      },
      // 为通过审核的志愿者
      {
        path: '/noChecked',
        component: () => import('@/views/volunteer/NoCheckVolunteer.vue')
      },
      // 活动审核
      {
        path: '/orderactivity',
        component: () => import('@/views/activity/OrderActivity.vue')
      },
      // 预约成功
      {
        path: '/orderSuccess',
        component: () => import('@/views/activity/OrderSuccess.vue')
      },
      // 预约失败
      {
        path: '/orderDefeat',
        component: () => import('@/views/activity/OrderDefeat.vue')
      }
    ]
  },
  // 登录
  {
    path: '/login',
    component: () => import('../views/loginregister/Login.vue')
  },
  // 注册
  {
    path: '/register',
    component: () => import('../views/loginregister/Register.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

router.beforeEach((to, from, next) => {
  const token:string | null = localStorage.getItem('token')
  if (!token) {
    if (to.path === '/login' || to.path === '/register') {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
